package com.bluesky.drcp.persistence.dao.hibernate;

import java.util.Iterator;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.bluesky.drcp.business.FunctionAuthorization;
import com.bluesky.drcp.persistence.dao.FunctionAuthorizationDao;

public class FunctionAuthorizationDaoImpl extends HibernateDaoSupport implements
		FunctionAuthorizationDao {

	public boolean isUserAuthorized(String userId, String functionId) {
		Object[] p = new Object[] { userId, functionId };
		List list = getHibernateTemplate()
				.find(
						"select fa from UserRole ur,FunctionAuthorization fa where ur.userId=? and ur.roleId=fa.roleId and fa.functionId=?",
						p);

		return (!list.isEmpty());
	}

	public boolean isRoleAuthorized(String roleId, String functionId) {
		Object[] p = new Object[] { roleId, functionId };
		List list = getHibernateTemplate()
				.find(
						"from FunctionAuthorization where roleId=? and functionId=?",
						p);

		return (!list.isEmpty());
	}

	public List getAuthorizedFunctions(String roleId) {
		return getHibernateTemplate()
				.find(
						"select f from FunctionAuthorization fa, Function f where fa.functionId=f.id and fa.roleId=?",
						roleId);

	}

	public void setAuthorizedFunctions(String roleId, List functionIds) {
		deleteByRoleId(roleId);
		
		Iterator it = functionIds.iterator();
		while(it.hasNext()){
			String functionId = (String)it.next();
		
			FunctionAuthorization fa = new FunctionAuthorization();
			fa.setRoleId(roleId);
			fa.setFunctionId(functionId);
			
			save(fa);
		}		
	}

	public void save(FunctionAuthorization functionAuthorization) {
		getHibernateTemplate().save(functionAuthorization);		
	}

	public void deleteByFunctionId(String functionId) {
		getHibernateTemplate().bulkUpdate("delete from FunctionAuthorization where functionId=?", functionId);		
	}

	public void deleteByRoleId(String roleId) {
		getHibernateTemplate().bulkUpdate("delete from FunctionAuthorization where roleId=?", roleId);
		
	}
	
	

}
